package com.jy.appmarket.cards;

import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.jy.app.market.idata.card.CardApkRecommend;
import com.jy.app.market.idata.data.Apk;
import com.jy.appmarket.AppMarketApplication;
import com.jy.appmarket.R;
import com.jy.appmarket.activity.AppDetailActivity;
import com.jy.appmarket.download.DownloadActivity;
import com.jy.appmarket.download.DownloadItem;
import com.jy.appmarket.download.DownloadService;
import com.jy.appmarket.download.DownloadUtils;
import com.jy.appmarket.statistics.ApkSource;
import com.jy.appmarket.utils.IdataUtils;
import com.jy.appmarket.utils.LoadImageUtils;
import com.jy.appmarket.utils.LogUtil;
import com.jy.appmarket.utils.PackageUtils;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * 类说明：
 * 
 * @author Baker.li
 * @date 2015年8月21日
 * @version 1.0
 */

public class ApkRecommendUICard extends DownloadableUICard {
	private static final String TAG = ApkRecommendUICard.class.getSimpleName();
	private DownloadActivity mDLActivity;
	private int apkCount = 0;
	private AppHolder[] mHolders;
	private CardApkRecommend mApkRecommend;

	private int mNameLines = 1;
	private float mTextViewWidth = 0;

	private int mBlueTextColor;
	private int mOrangeTextColor;
	private int mGrayTextColor;

	public ApkRecommendUICard(Context context, CardApkRecommend apkRecommend) {
		super(context, R.layout.apk_recommend_card);
		mDLActivity = (DownloadActivity) context;
		mApkRecommend = apkRecommend;
		init();
	}

	private void init() {
		if (mApkRecommend == null) {
			return;
		}
		List<Apk> apks = mApkRecommend.getApks();
		if (apks == null || apks.size() == 0) {
			return;
		}
		if (apks.size() >= 3) {
			apkCount = 3;
		} else {
			apkCount = apks.size();
		}

		mHolders = new AppHolder[apkCount];
		for (int i = 0; i < apkCount; i++) {
			mHolders[i] = new AppHolder();
			Apk apk = mApkRecommend.getApks().get(i);
			String dlId = DownloadUtils.generateDownloadId(apk.getPackageName(),
					apk.getVersionCode());
			String icon = IdataUtils.getIconUrl(apk.getIcons());
			mHolders[i].iconUrl = icon;
			mHolders[i].apk = apk;
			mHolders[i].dlId = dlId;
			mHolders[i].downloadItem = mDLActivity.getDownloadById(dlId);
		}

		mTextViewWidth = getContext().getResources().getDimension(R.dimen.list_app_icon_width);

		mBlueTextColor = getContext().getResources().getColor(R.color.download_btn_blue_style_text);
		mOrangeTextColor = getContext().getResources().getColor(
				R.color.download_btn_orange_style_text);
		mGrayTextColor = getContext().getResources().getColor(R.color.download_btn_gray_style_text);
	}

	@Override
	public int getType() {
		return 7;
	}

	@Override
	public void setupInnerViewElements(ViewGroup parent, View view) {
		if (mApkRecommend == null) {
			return;
		}
		TextView title = parent.findViewById(R.id.apk_recommend_header_title);
		title.setText(mApkRecommend.getTitle());

		View[] apkViews = new View[] { parent.findViewById(R.id.apk_recommend_apk1),
				parent.findViewById(R.id.apk_recommend_apk2),
				parent.findViewById(R.id.apk_recommend_apk3) };

		for (int i = 0; i < apkViews.length; i++) {
			apkViews[i].setVisibility(i < apkCount ? View.VISIBLE : View.INVISIBLE);
		}

		for (int i = 0; i < apkCount; i++) {
			TextView nameView = apkViews[i].findViewById(R.id.app_item_lite_name);
			float textWidth = computeStringWidth(mHolders[i].apk.getTitle(), nameView.getPaint());
			if (textWidth > mTextViewWidth) {
				mNameLines = 2;
				break;
			}
		}

		for (int i = 0; i < apkCount; i++) {
			mHolders[i].button = apkViews[i]
					.findViewById(R.id.app_item_lite_download_button);
			mHolders[i].icon = apkViews[i].findViewById(R.id.app_item_lite_icon);
			mHolders[i].install = apkViews[i]
					.findViewById(R.id.app_item_lite_installcount);
			mHolders[i].progressBar = apkViews[i]
					.findViewById(R.id.app_item_lite_progressbar);

			mHolders[i].name = apkViews[i].findViewById(R.id.app_item_lite_name);
			mHolders[i].name.setMinLines(mNameLines);
			mHolders[i].name.setMaxLines(mNameLines);

			mHolders[i].name.setText((AppMarketApplication.showLocal
					& mHolders[i].apk.getLocal() > 0 ? "★" : "")
					+ mHolders[i].apk.getTitle());
			ImageLoader.getInstance().displayImage(mHolders[i].iconUrl, mHolders[i].icon,
					LoadImageUtils.getListIconDisplayOption(mDLActivity));

			final int index = i;
			apkViews[i].setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					Apk apk = mHolders[index].apk;
					Intent detail = new Intent(mDLActivity, AppDetailActivity.class);
					detail.putExtra(AppDetailActivity.EXTRA_NAME, apk.getTitle());
					detail.putExtra(AppDetailActivity.EXTRA_PKG, apk.getPackageName());
					detail.putExtra(AppDetailActivity.EXTRA_SOURCE,
							ApkSource.toSourceString(getApkSource()));
					mDLActivity.startActivity(detail);
				}
			});
			setupApkView(mHolders[i]);
		}
	}

	private void setupApkView(final AppHolder h) {
		if (h.button == null) {
			return;
		}

		Apk apk = h.apk;
		// int status = mDLActivity.getDownloadStatus(h.dlId,
		// apk.getPackageName());
		int status = mDLActivity.getDownloadStatus(h.dlId, apk.getPackageName(),
				apk.getVersionCode());

		switch (status) {
		case DownloadService.STATUS_CAN_INSTALL:
			h.install.setVisibility(View.VISIBLE);
			h.progressBar.setVisibility(View.GONE);

			h.install.setText(R.string.wait_for_install);

			h.button.setBackgroundResource(R.drawable.download_button_blue);
			h.button.setTextColor(mBlueTextColor);
			h.button.setText(R.string.install);
			h.button.setClickable(true);
			break;

		case DownloadService.STATUS_PAUSED_BY_ERROR:
			h.install.setVisibility(View.GONE);
			h.progressBar.setVisibility(View.VISIBLE);

			h.progressBar.setIndeterminate(false);
			h.progressBar.setProgress(getProgress(h.downloadItem, h.apk, h.dlId));

			h.button.setTextColor(mOrangeTextColor);
			h.button.setBackgroundResource(R.drawable.download_button_orange);
			h.button.setText(R.string.retry);
			h.button.setClickable(true);

			break;
		case DownloadService.STATUS_INSTALLED:
			h.install.setVisibility(View.VISIBLE);
			h.progressBar.setVisibility(View.GONE);

			h.install.setText(h.apk.getInstalledCountStr() + "人安装");

			h.button.setTextColor(mGrayTextColor);
			h.button.setBackgroundResource(R.drawable.download_button_gray);
			h.button.setText(R.string.open);
			h.button.setClickable(true);
			break;
		case DownloadService.STATUS_NO_STATUS:
			h.install.setVisibility(View.VISIBLE);
			h.progressBar.setVisibility(View.GONE);

			h.install.setText(h.apk.getInstalledCountStr() + "人安装");

			h.button.setTextColor(mBlueTextColor);
			h.button.setBackgroundResource(R.drawable.download_button_blue);
			h.button.setText(R.string.download);
			h.button.setClickable(true);
			break;
		case DownloadService.STATUS_PAUSED_BY_MOBILE_NETWORK:
			h.install.setVisibility(View.GONE);
			h.progressBar.setVisibility(View.VISIBLE);

			h.progressBar.setIndeterminate(false);
			h.progressBar.setProgress(getProgress(h.downloadItem, h.apk, h.dlId));

			h.button.setTextColor(mBlueTextColor);
			h.button.setBackgroundResource(R.drawable.download_button_blue);
			h.button.setText(R.string.go_on);
			h.button.setClickable(true);

			break;
		case DownloadService.STATUS_PAUSED_BY_USER:
			h.install.setVisibility(View.GONE);
			h.progressBar.setVisibility(View.VISIBLE);

			h.progressBar.setIndeterminate(false);
			h.progressBar.setProgress(getProgress(h.downloadItem, h.apk, h.dlId));

			h.button.setTextColor(mBlueTextColor);
			h.button.setBackgroundResource(R.drawable.download_button_blue);
			h.button.setText(R.string.go_on);
			h.button.setClickable(true);

			break;
		case DownloadService.STATUS_DOWNLOADING:
			h.install.setVisibility(View.GONE);
			h.progressBar.setVisibility(View.VISIBLE);

			h.progressBar.setIndeterminate(false);
			h.progressBar.setProgress(getProgress(h.downloadItem, h.apk, h.dlId));

			h.button.setTextColor(mGrayTextColor);
			h.button.setBackgroundResource(R.drawable.download_button_gray);
			h.button.setText(R.string.pause);
			h.button.setClickable(true);

			break;

		case DownloadService.STATUS_PREPARE_TO_DOWNLOAD:
			h.install.setVisibility(View.GONE);
			h.progressBar.setVisibility(View.VISIBLE);

			h.progressBar.setIndeterminate(true);

			h.button.setTextColor(mGrayTextColor);
			h.button.setBackgroundResource(R.drawable.download_button_gray);
			h.button.setText(R.string.pause);
			h.button.setClickable(false);
			break;
		case DownloadService.STATUS_PREPARE_TO_STOP:
			h.install.setVisibility(View.GONE);
			h.progressBar.setVisibility(View.VISIBLE);

			h.progressBar.setIndeterminate(true);

			h.button.setTextColor(mBlueTextColor);
			h.button.setBackgroundResource(R.drawable.download_button_gray);
			h.button.setText(R.string.go_on);
			h.button.setClickable(false);

			break;
		case DownloadService.STATUS_INSTALLING:
			h.install.setVisibility(View.GONE);
			h.progressBar.setVisibility(View.VISIBLE);

			h.progressBar.setIndeterminate(true);

			h.button.setTextColor(mBlueTextColor);
			h.button.setBackgroundResource(R.drawable.download_button_gray);
			h.button.setText(R.string.installing);
			h.button.setClickable(false);
			break;

		case DownloadService.STATUS_PENDING:
			h.install.setVisibility(View.GONE);
			h.progressBar.setVisibility(View.VISIBLE);

			h.progressBar.setIndeterminate(false);
			h.progressBar.setProgress(getProgress(h.downloadItem, h.apk, h.dlId));

			h.button.setTextColor(mGrayTextColor);
			h.button.setBackgroundResource(R.drawable.download_button_gray);
			h.button.setText(R.string.waiting);
			h.button.setClickable(true);

			break;
		case DownloadService.STATUS_DOWNLOAD_OUT_OF_DATE:
			h.install.setVisibility(View.VISIBLE);
			h.progressBar.setVisibility(View.GONE);

			h.install.setText(h.apk.getInstalledCountStr() + "人安装");

			h.button.setTextColor(mBlueTextColor);
			h.button.setBackgroundResource(R.drawable.download_button_blue);
			h.button.setClickable(true);
			if (PackageUtils.isPackageInstalled(mDLActivity, apk.getPackageName())) {
				h.button.setText(R.string.update);
			} else {
				h.button.setText(R.string.download);
			}
			break;
		case DownloadService.STATUS_NEED_TO_UPDATE:
			h.install.setVisibility(View.VISIBLE);
			h.progressBar.setVisibility(View.GONE);

			h.install.setText(h.apk.getInstalledCountStr() + "人安装");

			h.button.setTextColor(mBlueTextColor);
			h.button.setBackgroundResource(R.drawable.download_button_blue);
			h.button.setText(R.string.update);
			h.button.setClickable(true);
			break;
		default:
			LogUtil.w(TAG, "unknown status:" + status);
			break;
		}

		h.button.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// int status = mDLActivity.getDownloadStatus(h.dlId,
				// h.apk.getPackageName());
				int status = mDLActivity.getDownloadStatus(h.dlId, h.apk.getPackageName(),
						h.apk.getVersionCode());

				switch (status) {
				case DownloadService.STATUS_INSTALLED: {
					try {
						Intent intent = getContext().getPackageManager().getLaunchIntentForPackage(
								h.apk.getPackageName());
						mDLActivity.startActivity(intent);
					} catch (Exception e) {
						e.printStackTrace();
						Toast.makeText(mDLActivity, "打开失败", Toast.LENGTH_SHORT).show();
					}
				}
					break;

				case DownloadService.STATUS_CAN_INSTALL: {
					mDLActivity.installApk(h.downloadItem);
				}
					break;
				case DownloadService.STATUS_DOWNLOADING: {
					mDLActivity.stopDownload(h.dlId);
				}
					break;
				case DownloadService.STATUS_NO_STATUS: {

					mDLActivity.addDownload(h.apk.getDownloadUrl().getUrl(), h.apk.getTitle(),
							h.apk.getPackageName(), h.apk.getVersionName(), h.apk.getVersionCode(),
							h.apk.getMd5(), h.iconUrl, ApkSource.toSourceString(getApkSource()));
					if (DownloadUtils.isMobileNetwork(mDLActivity)) {
						Toast.makeText(mDLActivity, R.string.download_in_gprs, Toast.LENGTH_LONG)
								.show();
					}
				}
					break;

				case DownloadService.STATUS_PAUSED_BY_ERROR:
				case DownloadService.STATUS_PAUSED_BY_MOBILE_NETWORK:
				case DownloadService.STATUS_PAUSED_BY_USER:
					mDLActivity.startDownload(h.dlId);
					if (DownloadUtils.isMobileNetwork(mDLActivity)) {
						Toast.makeText(mDLActivity, R.string.download_in_gprs, Toast.LENGTH_LONG)
								.show();
					}
					break;
				case DownloadService.STATUS_PENDING:
					mDLActivity.stopDownload(h.dlId);
					break;
				case DownloadService.STATUS_DOWNLOAD_OUT_OF_DATE: // 下载过期状态，强制处理为有更新状态，点击后重新开始下载
					// mDLActivity.removeDownloadImmediately(h.dlId);
					// mDLActivity.removeDownloadFiles(h.apk.getDownloadUrl().getUrl());

					mDLActivity.removeOutofDateDownloads(h.apk.getPackageName());

					mDLActivity.addDownload(h.apk.getDownloadUrl().getUrl(), h.apk.getTitle(),
							h.apk.getPackageName(), h.apk.getVersionName(), h.apk.getVersionCode(),
							h.apk.getMd5(), h.iconUrl, ApkSource.toSourceString(getApkSource()));
					if (DownloadUtils.isMobileNetwork(mDLActivity)) {
						Toast.makeText(mDLActivity, R.string.download_in_gprs, Toast.LENGTH_LONG)
								.show();
					}
					break;
				case DownloadService.STATUS_NEED_TO_UPDATE:
					mDLActivity.addDownload(h.apk.getDownloadUrl().getUrl(), h.apk.getTitle(),
							h.apk.getPackageName(), h.apk.getVersionName(), h.apk.getVersionCode(),
							h.apk.getMd5(), h.iconUrl, ApkSource.toSourceString(getApkSource()));
					if (DownloadUtils.isMobileNetwork(mDLActivity)) {
						Toast.makeText(mDLActivity, R.string.download_in_gprs, Toast.LENGTH_LONG)
								.show();
					}
					break;
				default:
					break;
				}
			}
		});

	}

	@Override
	public void onPackageInstalled(String pkgName) {
		if (mHolders == null) {
			return;
		}
		boolean changed = false;
		for (AppHolder h : mHolders) {
			if (pkgName.equals(h.apk.getPackageName())) {
				changed = true;
			}
		}
		if (!changed) {
			return;
		}
		if (refreshList(getIndex())) {
			return;
		}
		for (AppHolder h : mHolders) {
			if (pkgName.equals(h.apk.getPackageName())) {
				setupApkView(h);
			}
		}
	}

	@Override
	public void onPackageUninstalled(String pkgName) {
		if (mHolders == null) {
			return;
		}
		boolean changed = false;
		for (AppHolder h : mHolders) {
			if (pkgName.equals(h.apk.getPackageName())) {
				changed = true;
			}
		}
		if (!changed) {
			return;
		}
		if (refreshList(getIndex())) {
			return;
		}
		for (AppHolder h : mHolders) {
			if (pkgName.equals(h.apk.getPackageName())) {
				setupApkView(h);
			}
		}
	}

	@Override
	public void onDownloadCreated(DownloadItem di) {
		if (mHolders == null) {
			return;
		}

		boolean changed = false;
		for (AppHolder h : mHolders) {
			if (di.getId().equals(h.dlId)) {
				h.downloadItem = di;
				changed = true;
			}
		}
		if (!changed) {
			return;
		}
		if (refreshList(getIndex())) {
			return;
		}
		for (AppHolder h : mHolders) {
			if (di.getId().equals(h.dlId)) {
				setupApkView(h);
			}
		}
	}

	@Override
	public void onDownloadRemoved(String id) {
		if (mHolders == null) {
			return;
		}
		boolean changed = false;
		for (AppHolder h : mHolders) {
			if (id.equals(h.dlId)) {
				h.downloadItem = null;
				changed = true;
			}
		}
		if (!changed) {
			return;
		}
		if (refreshList(getIndex())) {
			return;
		}
		for (AppHolder h : mHolders) {
			if (id.equals(h.dlId)) {
				setupApkView(h);
			}
		}

	}

	@Override
	public void onDownloadChanged(DownloadItem di) {
		if (mHolders == null) {
			return;
		}

		boolean changed = false;
		for (AppHolder h : mHolders) {
			if (di.getId().equals(h.dlId)) {
				h.downloadItem = di;
				changed = true;
			}
		}
		if (!changed) {
			return;
		}
		if (refreshList(getIndex())) {
			return;
		}
		for (AppHolder h : mHolders) {
			if (di.getId().equals(h.dlId)) {
				setupApkView(h);
			}
		}
	}

	@Override
	public void onProgressChanged(String id, long downloaded, long speed) {
		if (mHolders == null) {
			return;
		}
		boolean changed = false;
		for (AppHolder h : mHolders) {
			if (h.downloadItem == null) {
				continue;
			}
			if (id.equals(h.dlId)) {
				h.downloadItem.setDownloadedSize(downloaded);
				h.downloadItem.setSpeed(speed);
				changed = true;
			}
		}
		if (!changed) {
			return;
		}
		if (refreshList(getIndex())) {
			return;
		}
		for (AppHolder h : mHolders) {
			if (id.equals(h.dlId)) {
				setupApkView(h);
			}
		}
	}

	private static class AppHolder {
		private String dlId;
		private Apk apk;
		private String iconUrl;
		private DownloadItem downloadItem;
		private TextView install;
		private Button button;
		private ImageView icon;
		private TextView name;
		private ProgressBar progressBar;
	}

	private float computeStringWidth(String string, Paint p) {
		if (string == null) {
			return 0;
		}

		float width = p.measureText(string);
		return width;
	}

	// @Override
	// public int getMarginTop(){
	// return 0; //返回0，则在顶部没有空隙
	// }

}